<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 -->
    <header class="sticky top-0 z-50 bg-white shadow-md transition-all duration-300">
      <div class="container mx-auto px-4">
        <div class="flex items-center justify-between h-16 md:h-20">
          <!-- Logo -->
          <div class="flex items-center">
            <router-link to="/" class="flex items-center">
              <i class="fas fa-book text-primary text-2xl md:text-3xl mr-2"></i>
              <span class="text-xl md:text-2xl font-bold text-primary" style="font-weight: 700;">书香阁</span>
            </router-link>
          </div>

          <!-- 主导航 - 桌面版 -->
          <nav class="hidden md:flex items-center space-x-8">
            <router-link to="/home" class="font-medium text-primary border-b-2 border-primary py-1">首页</router-link>
            <router-link to="/category" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">分类</router-link>
            <router-link to="/bestseller" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">畅销榜</router-link>
            <router-link to="/news" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">资讯</router-link>
          </nav>

          <!-- 搜索框 -->
          <div class="hidden md:flex items-center flex-1 max-w-md mx-8">
            <div class="relative w-full flex">
              <el-input
                v-model="searchKeyword"
                placeholder="请输入您喜欢的商品"
                class="search-input flex-1"
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <i class="fas fa-search text-gray-400"></i>
                </template>
              </el-input>
              <button
                @click="handleSearch"
                class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
              >
                <i class="fas fa-search"></i>
              </button>
            </div>
          </div>

          <!-- 用户工具栏 -->
          <div class="flex items-center space-x-4">
            <button class="relative p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bell text-lg"></i>
              <span class="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full"></span>
            </button>
            <button
              @click="goToCart"
              class="relative p-2 text-gray-600 hover:text-primary transition-colors"
            >
              <i class="fas fa-shopping-cart text-lg"></i>
              <span class="absolute -top-1 -right-1 bg-primary text-white text-xs rounded-full w-5 h-5 flex items-center justify-center cart-badge">{{ cartCount }}</span>
            </button>

            <!-- 用户下拉菜单 -->
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link cursor-pointer flex items-center">
                <el-avatar :size="32" :src="getImageUrl(userStore.userInfo?.avatar)">
                  <i class="fas fa-user"></i>
                </el-avatar>
                <span class="hidden md:block ml-2 text-gray-600">{{ userStore.userInfo?.username }}</span>
                <i class="fas fa-chevron-down ml-1 text-gray-400"></i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                  <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                  <el-dropdown-item command="settings">设置</el-dropdown-item>
                  <el-dropdown-item v-if="userStore.isAdmin" command="admin" divided>
                    <i class="fas fa-cog mr-2"></i>管理后台
                  </el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 移动端菜单按钮 -->
            <button @click="toggleMobileMenu" class="md:hidden p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bars text-xl"></i>
            </button>
          </div>
        </div>

        <!-- 移动端搜索框 -->
        <div class="md:hidden pb-4">
          <div class="flex">
            <el-input
              v-model="searchKeyword"
              placeholder="请输入您喜欢的商品"
              class="search-input flex-1"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <i class="fas fa-search text-gray-400"></i>
              </template>
            </el-input>
            <button
              @click="handleSearch"
              class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
            >
              <i class="fas fa-search"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 移动端导航菜单 -->
      <div v-show="showMobileMenu" class="md:hidden bg-white border-t border-gray-100 shadow-lg">
        <div class="container mx-auto px-4 py-3 space-y-3">
          <router-link to="/home" class="block py-2 px-3 rounded-lg bg-primary/10 text-primary font-medium">首页</router-link>
          <router-link to="/category" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">分类</router-link>
          <router-link to="/bestseller" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">畅销榜</router-link>
          <router-link to="/news" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">资讯</router-link>
        </div>
      </div>
    </header>

    <!-- 主要内容 -->
    <main class="container mx-auto px-4 py-6">
      <!-- 主图区 -->
      <section class="mb-12 bg-gradient-to-r from-secondary/30 to-white rounded-2xl overflow-hidden shadow-sm">
        <div class="flex flex-col md:flex-row items-center">
          <div class="md:w-1/2 p-6 md:p-10 lg:p-12">
            <h1 class="text-[clamp(1.8rem,5vw,3rem)] font-bold leading-tight text-dark mb-4">
              发现阅读的<br><span style="color: rgb(255, 107, 139);">无限可能</span>
            </h1>
            <p class="text-gray-600 text-lg mb-8 max-w-lg">
              探索超过10万本精选图书，从经典文学到现代科技，满足您的每一个阅读需求。限时优惠，立即选购！
            </p>
            <div class="flex flex-wrap gap-4">
              <button
                style="background-color: #FF6B8B; color: white; transition: all 0.3s ease;" 
                class="px-6 py-3 rounded-full font-medium shadow-md hover-explore-btn"
                @click="handleExplore"
              >
                立即探索
              </button>
              <button
                style="color: rgb(255, 107, 139); background-color: #f9f9f9; border: 1px solid #FF6B8B; transition: all 0.3s ease;" 
                class="px-6 py-3 rounded-full font-medium hover-member-btn"
                @click="handleMembership"
              >
                了解会员权益
              </button>
            </div>
          </div>
          <div class="md:w-1/2 p-4 md:p-8">
            <img
              src="https://design.gemcoder.com/staticResource/echoAiSystemImages/f94fa5368ec54a9a1fafd8c376d0aa53.png"
              alt="书籍与树叶插画"
              class="w-full h-auto rounded-xl shadow-lg transform hover:scale-[1.02] transition-transform duration-500"
            >
          </div>
        </div>
      </section>

      <!-- 分类导航 -->
      <section class="mb-12">
        <div class="flex items-center justify-between mb-6">
          <h2 class="text-2xl font-bold text-gray-800">图书分类</h2>
          <router-link to="/category" class="text-primary flex items-center hover:underline transition-colors">
            查看全部 <i class="fas fa-chevron-right ml-1 text-sm"></i>
          </router-link>
        </div>

        <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
          <router-link
            v-for="category in categories"
            :key="category.id"
            to="/category"
            class="category-card bg-white rounded-xl p-4 text-center shadow-sm hover:shadow-md transition-all duration-300 transform hover:-translate-y-1 border border-gray-100 hover:border-primary/20"
          >
            <div class="w-12 h-12 bg-gradient-to-br from-primary/10 to-primary/5 rounded-full flex items-center justify-center mx-auto mb-3">
              <i :class="category.icon" class="text-primary text-xl"></i>
            </div>
            <span class="font-medium text-gray-700">{{ category.name }}</span>
          </router-link>
        </div>
      </section>

      <!-- 官方推荐区 -->
      <section class="mb-16">
        <div class="flex items-center justify-between mb-6">
          <h2 class="text-2xl font-bold text-gray-800">官方推荐</h2>
          <div class="flex space-x-2">
            <button
              @click="prevRecommend"
              class="w-10 h-10 rounded-full border border-gray-200 bg-white flex items-center justify-center hover:border-primary hover:text-primary hover:bg-gray-50 transition-all duration-300"
            >
              <i class="fas fa-chevron-left"></i>
            </button>
            <button
              @click="nextRecommend"
              class="w-10 h-10 rounded-full border border-gray-200 bg-white flex items-center justify-center hover:border-primary hover:text-primary hover:bg-gray-50 transition-all duration-300"
            >
              <i class="fas fa-chevron-right"></i>
            </button>
          </div>
        </div>

        <div class="overflow-hidden">
          <div
            ref="recommendSlider"
            class="flex space-x-6 transition-transform duration-500 ease-out"
            :style="{ transform: `translateX(-${recommendSlideIndex * slideWidth}px)` }"
          >
            <div
              v-for="book in recommendedBooks"
              :key="book.id"
              @click="goToBookDetail(book.id)"
              class="min-w-[240px] sm:min-w-[280px] bg-white rounded-xl overflow-hidden shadow-sm hover:shadow-lg transition-all duration-300 transform hover:-translate-y-2 border border-gray-100 cursor-pointer"
            >
              <div class="relative">
                <img
                  :src="book.cover"
                  :alt="book.title"
                  class="w-full h-64 object-cover"
                >
                <div v-if="book.tag" :class="`absolute top-3 left-3 text-white text-xs font-bold px-2 py-1 rounded ${book.tagColor}`">
                  {{ book.tag }}
                </div>
              </div>
              <div class="p-4">
                <h3 class="font-bold text-lg mb-1 line-clamp-1 text-gray-800">{{ book.title }}</h3>
                <p class="text-gray-500 text-sm mb-2 line-clamp-1">作者：{{ book.author }}</p>
                <p class="text-gray-600 text-sm mb-3 line-clamp-2">{{ book.description }}</p>
                <div class="flex items-center justify-between">
                  <span class="text-primary font-bold text-xl">¥{{ book.price }}</span>
                  <button
                  @click.stop="addToCart(book)"
                  class="w-8 h-8 rounded-full bg-primary/10 text-primary flex items-center justify-center hover:bg-primary hover:text-white transition-colors"
                >
                  <i class="fas fa-shopping-cart text-sm"></i>
                </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <!-- 新书上架 -->
      <section class="mb-16">
        <div class="flex items-center justify-between mb-6">
          <h2 class="text-2xl font-bold text-gray-800">新书上架</h2>
          <button @click="showMoreNewBooks" class="text-primary flex items-center hover:underline transition-colors">
            更多新品 <i class="fas fa-chevron-right ml-1 text-sm"></i>
          </button>
        </div>

        <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-5">
          <div
            v-for="book in displayedNewBooks"
            :key="book.id"
            @click="goToBookDetail(book.id)"
            class="bg-white rounded-xl overflow-hidden shadow-sm hover:shadow-lg transition-all duration-300 transform hover:-translate-y-1 border border-gray-100 cursor-pointer"
          >
            <div class="relative">
              <img
                :src="book.cover"
                :alt="book.title"
                class="w-full h-56 object-cover"
              >
              <div v-if="book.tag" :class="`absolute top-3 left-3 text-white text-xs font-bold px-2 py-1 rounded ${book.tagColor}`">
                {{ book.tag }}
              </div>
            </div>
            <div class="p-3">
              <h3 class="font-bold text-base mb-1 line-clamp-1 text-gray-800">{{ book.title }}</h3>
              <p class="text-gray-500 text-xs mb-2 line-clamp-1">作者：{{ book.author }}</p>
              <div class="flex items-center justify-between">
                <span class="text-primary font-bold">¥{{ book.price }}</span>
                <button
                  @click.stop="addToCart(book)"
                  class="w-8 h-8 rounded-full bg-primary/10 text-primary flex items-center justify-center hover:bg-primary hover:text-white transition-colors"
                >
                  <i class="fas fa-shopping-cart text-sm"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </section>

      <!-- 促销活动 -->
      <section class="mb-16">
        <div class="bg-gradient-to-r from-primary to-pink-400 rounded-2xl overflow-hidden shadow-lg">
          <div class="flex flex-col md:flex-row items-center">
            <div class="md:w-1/2 p-8 md:p-12 text-white">
              <h2 class="text-3xl md:text-4xl font-bold mb-4">夏日阅读季</h2>
              <p class="text-white/90 text-lg mb-6 max-w-md">精选图书满100减30，满200减80，更有会员专享折上折！</p>
              <div class="flex space-x-4 mb-8">
                <div class="bg-white/20 backdrop-blur-sm rounded-lg p-3 text-center min-w-[80px]">
                  <div class="text-2xl font-bold">{{ countdown.days }}</div>
                  <div class="text-sm text-white/80">天</div>
                </div>
                <div class="bg-white/20 backdrop-blur-sm rounded-lg p-3 text-center min-w-[80px]">
                  <div class="text-2xl font-bold">{{ countdown.hours }}</div>
                  <div class="text-sm text-white/80">时</div>
                </div>
                <div class="bg-white/20 backdrop-blur-sm rounded-lg p-3 text-center min-w-[80px]">
                  <div class="text-2xl font-bold">{{ countdown.minutes }}</div>
                  <div class="text-sm text-white/80">分</div>
                </div>
                <div class="bg-white/20 backdrop-blur-sm rounded-lg p-3 text-center min-w-[80px]">
                  <div class="text-2xl font-bold">{{ countdown.seconds }}</div>
                  <div class="text-sm text-white/80">秒</div>
                </div>
              </div>
              <button
                style="background-color: white; color: #FF6B8B; transition: all 0.3s ease;" 
                class="px-8 py-3 rounded-full font-bold shadow-lg hover-promotion-btn"
                @click="handlePromotion"
              >
                立即抢购
              </button>
            </div>
            <div class="md:w-1/2 p-4 md:p-8">
              <img
                src="https://design.gemcoder.com/staticResource/echoAiSystemImages/f8541d8032cfc3a872d95e518435156a.png"
                alt="夏日阅读季促销"
                class="w-full h-auto rounded-xl shadow-lg transform hover:scale-[1.02] transition-transform duration-500"
              >
            </div>
          </div>
        </div>
      </section>

      <!-- 猜你喜欢区 -->
      <section class="mb-16">
        <div class="flex items-center justify-between mb-6">
          <h2 class="text-2xl font-bold text-gray-800">猜你喜欢</h2>
          <button
            @click="refreshRecommendations"
            class="text-primary flex items-center hover:underline transition-colors"
            :disabled="refreshing"
          >
            <i :class="['fas', 'fa-sync-alt', 'mr-1', { 'fa-spin': refreshing }]"></i>
            {{ refreshing ? '加载中...' : '换一批' }}
          </button>
        </div>

        <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
          <div
            v-for="book in displayedLikedBooks"
            :key="book.id"
            @click="goToBookDetail(book.id)"
            class="bg-white rounded-xl overflow-hidden shadow-sm hover:shadow-lg transition-all duration-300 transform hover:-translate-y-1 border border-gray-100 cursor-pointer"
          >
            <div class="relative">
              <img
                :src="book.cover"
                :alt="book.title"
                class="w-full h-48 object-cover"
              >
              <div v-if="book.tag" :class="`absolute top-3 left-3 text-white text-xs font-bold px-2 py-1 rounded ${book.tagColor}`">
                {{ book.tag }}
              </div>
            </div>
            <div class="p-3">
              <h3 class="font-bold text-sm mb-1 line-clamp-1 text-gray-800">{{ book.title }}</h3>
              <p class="text-gray-500 text-xs mb-1 line-clamp-1">{{ book.author }}</p>
              <div class="flex items-center justify-between">
                <span class="text-primary font-bold text-sm">¥{{ book.price }}</span>
                <button
                  @click.stop="addToCart(book)"
                  class="w-8 h-8 rounded-full bg-primary/10 text-primary flex items-center justify-center hover:bg-primary hover:text-white transition-colors"
                >
                  <i class="fas fa-shopping-cart text-sm"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </section>

      

      <!-- 订阅图书资讯 -->
      <section class="mb-16 bg-white rounded-2xl p-6 shadow-sm">
        <div class="flex flex-col md:flex-row items-center justify-between">
          <div class="mb-4 md:mb-0">
            <h2 class="text-xl font-bold text-dark mb-2">订阅我们的新书资讯</h2>
            <p class="text-gray-600">第一时间获取新书上架、促销活动和阅读指南</p>
          </div>
          <div class="flex w-full md:w-auto">
            <input
              type="email"
              placeholder="请输入您的邮箱地址"
              class="border border-gray-300 focus:border-primary rounded-l-full px-4 py-2 w-full md:w-64 outline-none"
            />
            <button class="bg-accent text-white rounded-r-full px-6 py-2 shadow-md whitespace-nowrap subscribe-btn" style="transform: translateY(-1px);">
              立即订阅
            </button>
          </div>
        </div>
      </section>
    </main>

    <!-- 底部页脚 -->
    <footer class="bg-gray-900 text-white py-10">
      <div class="container mx-auto px-4">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
          <!-- 关于我们 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">关于书香阁</h3>
            <p class="text-gray-400 text-sm">
              书香阁是专业的网上书店，提供超过10万种图书在线购买，支持快递配送和自提服务，让阅读触手可及。
            </p>
            <div class="flex space-x-4 mt-4">
              <a href="#" class="text-gray-400 hover:text-primary"><i class="fab fa-weixin text-xl"></i></a>
              <a href="#" class="text-gray-400 hover:text-primary"><i class="fab fa-weibo text-xl"></i></a>
              <a href="#" class="text-gray-400 hover:text-primary"><i class="fab fa-qq text-xl"></i></a>
              <a href="#" class="text-gray-400 hover:text-primary"><i class="fas fa-envelope text-xl"></i></a>
            </div>
          </div>

          <!-- 快捷链接 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">快捷链接</h3>
            <ul class="space-y-2 text-sm">
              <li><router-link to="/category" class="text-gray-400 hover:text-primary">分类浏览</router-link></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">热门排行</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">最新上架</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">特价促销</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">读者推荐</a></li>
            </ul>
          </div>

          <!-- 客户服务 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">客户服务</h3>
            <ul class="space-y-2 text-sm">
              <li><a href="#" class="text-gray-400 hover:text-primary">常见问题</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">配送方式</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">支付方式</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">退换政策</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">联系我们</a></li>
            </ul>
          </div>

          <!-- 联系方式 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">联系我们</h3>
            <ul class="space-y-3 text-sm">
              <li class="flex items-start">
                <i class="fas fa-map-marker-alt text-primary mt-1 mr-3"></i>
                <span class="text-gray-400">北京市朝阳区建国路88号</span>
              </li>
              <li class="flex items-center">
                <i class="fas fa-phone text-primary mr-3"></i>
                <span class="text-gray-400">400-800-1234</span>
              </li>
              <li class="flex items-center">
                <i class="fas fa-envelope text-primary mr-3"></i>
                <span class="text-gray-400">service@bookstore.com</span>
              </li>
              <li class="flex items-center">
                <i class="fas fa-clock text-primary mr-3"></i>
                <span class="text-gray-400">周一至周日 9:00-22:00</span>
              </li>
            </ul>
          </div>
        </div>

        <!-- 版权信息 -->
        <div class="border-t border-gray-800 mt-8 pt-8 flex flex-col md:flex-row justify-between items-center">
          <div class="text-gray-500 text-sm mb-4 md:mb-0">
            © {{ new Date().getFullYear() }} 书香阁 版权所有 | 京ICP备12345678号
          </div>
          <div class="flex space-x-4">
            <a href="#" class="text-gray-500 text-sm hover:text-primary">隐私政策</a>
            <a href="#" class="text-gray-500 text-sm hover:text-primary">使用条款</a>
            <a href="#" class="text-gray-500 text-sm hover:text-primary">网站地图</a>
          </div>
        </div>
      </div>
    </footer>

    <!-- 回到顶部按钮 -->
    <BackToTop />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import { ElMessage } from 'element-plus'
import ggbondImg from '@/assets/images/ggbond.png'
import BackToTop from '@/components/BackToTop.vue'
import { bookAPI } from '@/api/book.js'

const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()

// 响应式数据
const searchKeyword = ref('')
const showMobileMenu = ref(false)
const recommendSlideIndex = ref(0)
const slideWidth = ref(304) // 280px + 24px margin
const recommendSlider = ref(null)

// 计算购物车数量，使用cartStore
const cartCount = computed(() => cartStore.cartCount)

// 图书分类数据
const categories = reactive([])

// 分类图标映射
const categoryIconMap = {
  '外语学习': 'fas fa-language',
  '哲学宗教': 'fas fa-brain',
  '儿童读物': 'fas fa-child',
  '科学技术': 'fas fa-flask',
  '文学小说': 'fas fa-heart',
  '教育教材': 'fas fa-graduation-cap',
  '计算机': 'fas fa-laptop-code',
  '历史': 'fas fa-history',
  '艺术': 'fas fa-palette',
  '经济管理': 'fas fa-chart-line',
  '医学': 'fas fa-stethoscope',
  '法律': 'fas fa-balance-scale'
}

// 推荐图书数据
const recommendedBooks = reactive([])

// 新书上架数据
const newBooks = reactive([])
const allNewBooks = reactive([]) // 存储所有新书数据
const showAllNewBooks = ref(false) // 控制是否显示所有新书

// 猜你喜欢数据
const likedBooks = reactive([])
const allLikedBooks = reactive([]) // 存储所有个性化推荐数据

// 倒计时数据
const countdown = reactive({
  days: '15',
  hours: '08',
  minutes: '45',
  seconds: '33'
})

// 其他状态
const refreshing = ref(false)

// 方法
const toggleMobileMenu = () => {
  showMobileMenu.value = !showMobileMenu.value
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    ElMessage.info(`搜索功能开发中，搜索关键词：${searchKeyword.value}`)
  }
}

const prevRecommend = () => {
  if (recommendSlideIndex.value > 0) {
    recommendSlideIndex.value--
  }
}

const nextRecommend = () => {
  const maxIndex = Math.max(0, recommendedBooks.length - getVisibleSlides())
  if (recommendSlideIndex.value < maxIndex) {
    recommendSlideIndex.value++
  }
}

const getVisibleSlides = () => {
  if (!recommendSlider.value) return 1
  const containerWidth = recommendSlider.value.parentElement.clientWidth
  return Math.max(1, Math.floor(containerWidth / slideWidth.value))
}

const handleExplore = () => {
  ElMessage.info('探索功能开发中...')
}

const handleMembership = () => {
  ElMessage.info('会员权益功能开发中...')
}

const handlePromotion = () => {
  ElMessage.info('促销活动功能开发中...')
}

// 添加到购物车方法修改
const addToCart = async (book) => {
  try {
    await cartStore.addToCart(book)
    // 消息提示已在store中处理，这里不需要重复提示
  } catch (error) {
    console.error('添加到购物车失败:', error)
  }
}

// 计算属性：显示的新书（默认5本）
const displayedNewBooks = computed(() => {
  return showAllNewBooks.value ? newBooks : newBooks.slice(0, 5)
})

// 计算属性：显示的猜你喜欢（默认6本）
const displayedLikedBooks = computed(() => {
  return likedBooks.slice(0, 6)
})

const refreshRecommendations = async () => {
  refreshing.value = true
  try {
    // 如果有足够的数据，从现有数据中随机选择
    if (allLikedBooks.length >= 12) {
      const shuffledBooks = [...allLikedBooks].sort(() => Math.random() - 0.5)
      likedBooks.splice(0, likedBooks.length, ...shuffledBooks.slice(0, 6))
      ElMessage.success('推荐已更新')
    } else {
      // 如果数据不够，重新加载
      const personalizedRes = await bookAPI.getPersonalizedBooks(24)

      if (personalizedRes && personalizedRes.code === 200) {
        const books = personalizedRes.data.map(book => ({
          ...book,
          price: book.price ? book.price.toString() : '0.00',
          cover: getImageUrl(book.cover) || ggbondImg,
          tag: book.tags && book.tags.length > 0 ? book.tags[0].name : '推荐',
          tagColor: book.tags && book.tags.length > 0 ? book.tags[0].tagColor : 'bg-blue-500'
        }))
        // 更新所有数据
        allLikedBooks.splice(0, allLikedBooks.length, ...books)
        // 随机选择6本显示
        const shuffledBooks = [...books].sort(() => Math.random() - 0.5)
        likedBooks.splice(0, likedBooks.length, ...shuffledBooks.slice(0, 6))
        ElMessage.success('推荐已更新')
      } else {
        ElMessage.error('刷新推荐失败')
      }
    }
  } catch (error) {
    console.error('刷新推荐失败:', error)
    ElMessage.error('刷新推荐失败，请稍后重试')
  } finally {
    refreshing.value = false
  }
}

const goToBookDetail = (bookId) => {
  router.push(`/book/${bookId}`)
}

// 更多新品点击事件
const showMoreNewBooks = () => {
  // 跳转到新书上架页面
  router.push('/new-books')
}

const goToCart = () => {
  router.push('/cart')
}

// 倒计时更新
const updateCountdown = () => {
  const now = new Date()
  // 设置活动结束时间为30天后
  const endTime = new Date('2025-08-17 23:59:59')

  const diff = endTime - now
  if (diff > 0) {
    countdown.days = Math.floor(diff / (1000 * 60 * 60 * 24)).toString().padStart(2, '0')
    countdown.hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString().padStart(2, '0')
    countdown.minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0')
    countdown.seconds = Math.floor((diff % (1000 * 60)) / 1000).toString().padStart(2, '0')
  } else {
    // 活动结束时显示00
    countdown.days = '00'
    countdown.hours = '00'
    countdown.minutes = '00'
    countdown.seconds = '00'
  }
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'orders':
      router.push('/orders')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'admin':
      router.push('/admin')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 处理登出
const handleLogout = async () => {
  await userStore.logout()
  router.push('/login')
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `/api${url}`
}

// 数据加载函数
const loadBookData = async () => {
  try {
    // 并行加载三个板块的数据
    const [recommendedRes, newBooksRes, personalizedRes] = await Promise.all([
      bookAPI.getRecommendedBooks(10),
      bookAPI.getNewBooks(20), // 获取更多新书数据
      bookAPI.getPersonalizedBooks(24) // 获取更多个性化推荐数据
    ])

    console.log('API响应数据:', { recommendedRes, newBooksRes, personalizedRes })

    // 处理推荐图书数据
    if (recommendedRes && recommendedRes.code === 200) {
      const books = recommendedRes.data.map(book => ({
        ...book,
        price: book.price ? book.price.toString() : '0.00',
        cover: getImageUrl(book.cover) || ggbondImg,
        tag: book.tags && book.tags.length > 0 ? book.tags[0].name : '推荐',
        tagColor: book.tags && book.tags.length > 0 ? book.tags[0].tagColor : 'bg-pink-500'
      }))
      recommendedBooks.splice(0, recommendedBooks.length, ...books)
      console.log('推荐图书数据已加载:', books.length, '本')
    } else {
      console.error('推荐图书API响应异常:', recommendedRes)
    }

    // 处理新书数据
    if (newBooksRes && newBooksRes.code === 200) {
      const books = newBooksRes.data.map(book => ({
        ...book,
        price: book.price ? book.price.toString() : '0.00',
        cover: getImageUrl(book.cover) || ggbondImg,
        tag: book.tags && book.tags.length > 0 ? book.tags[0].name : '新书',
        tagColor: book.tags && book.tags.length > 0 ? book.tags[0].tagColor : 'bg-orange-500'
      }))
      // 存储所有新书数据
      allNewBooks.splice(0, allNewBooks.length, ...books)
      // 默认显示前5本
      newBooks.splice(0, newBooks.length, ...books)
      console.log('新书数据已加载:', books.length, '本')
    } else {
      console.error('新书API响应异常:', newBooksRes)
    }

    // 处理个性化推荐数据
    if (personalizedRes && personalizedRes.code === 200) {
      const books = personalizedRes.data.map(book => ({
        ...book,
        price: book.price ? book.price.toString() : '0.00',
        cover: getImageUrl(book.cover) || ggbondImg,
        tag: book.tags && book.tags.length > 0 ? book.tags[0].name : '推荐',
        tagColor: book.tags && book.tags.length > 0 ? book.tags[0].tagColor : 'bg-blue-500'
      }))
      // 存储所有个性化推荐数据
      allLikedBooks.splice(0, allLikedBooks.length, ...books)
      // 随机选择6本显示
      const shuffledBooks = [...books].sort(() => Math.random() - 0.5)
      likedBooks.splice(0, likedBooks.length, ...shuffledBooks.slice(0, 6))
      console.log('个性化推荐数据已加载:', books.length, '本，显示:', likedBooks.length, '本')
    } else {
      console.error('个性化推荐API响应异常:', personalizedRes)
    }

  } catch (error) {
    console.error('加载图书数据失败:', error)
    ElMessage.error('加载图书数据失败，请刷新页面重试')
  }
}

// 加载分类数据
const loadCategories = async () => {
  try {
    const response = await bookAPI.getCategories()
    if (response && response.code === 200) {
      const categoryData = response.data
        .map(category => ({
          ...category,
          icon: categoryIconMap[category.name] || 'fas fa-book'
        }))
        .slice(0, 6) // 只显示前6个分类
      categories.splice(0, categories.length, ...categoryData)
    }
  } catch (error) {
    console.error('加载分类数据失败:', error)
    // 如果加载失败，使用默认分类数据
    const defaultCategories = [
      { id: 1, name: '外语学习', icon: 'fas fa-language' },
      { id: 2, name: '哲学宗教', icon: 'fas fa-brain' },
      { id: 3, name: '儿童读物', icon: 'fas fa-child' },
      { id: 4, name: '科学技术', icon: 'fas fa-flask' },
      { id: 5, name: '文学小说', icon: 'fas fa-heart' },
      { id: 6, name: '教育教材', icon: 'fas fa-graduation-cap' }
    ]
    categories.splice(0, categories.length, ...defaultCategories)
  }
}

// 生命周期
onMounted(async () => {
  // 加载分类数据
  await loadCategories()
  // 加载图书数据
  await loadBookData()

  nextTick(() => {
    // 初始化轮播位置
    window.addEventListener('resize', () => {
      const maxIndex = Math.max(0, recommendedBooks.length - getVisibleSlides())
      if (recommendSlideIndex.value > maxIndex) {
        recommendSlideIndex.value = maxIndex
      }
    })

    // 启动倒计时
    updateCountdown()
    setInterval(updateCountdown, 1000)
  })
})
</script>

<style scoped>
/* 自定义样式 */
:root {
  --primary: #FF6B8A;
  --primary-light: #FFB3C6;
  --primary-dark: #E55A7A;
  --secondary: #FFF0F3;
  --accent: #FF8FA3;
  --success: #4CAF50;
  --warning: #FF9800;
  --info: #2196F3;
  --dark: #2D3748;
  --gray: #718096;
  --light-gray: #F7FAFC;
  --white: #FFFFFF;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  color: #606266;
  transition: color 0.3s ease;
}

.el-dropdown-link:hover {
  color: var(--primary);
}

/* 搜索框样式 */
.search-input :deep(.el-input__wrapper) {
  border-radius: 9999px;
  border: 1px solid #d1d5db;
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper):hover {
  border-color: var(--primary);
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(255, 107, 139, 0.2);
}

/* 搜索按钮样式 */
.search-button {
  background-color: #FF6B8B !important;
}

.search-button:hover {
  background-color: rgba(255, 107, 139, 0.8) !important;
}

/* 分类卡片动画 */
.category-card {
  transition: all 0.3s ease;
}

.category-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

/* 文本截断 */
.line-clamp-1 {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 主题色定义 */
.text-primary {
  color: rgb(255, 107, 139) !important;
}

.bg-primary {
  background-color: #FF6B8B !important;
}

.border-primary {
  border-color: #FF6B8B !important;
}

.text-secondary {
  color: var(--secondary);
}

.bg-secondary\/30 {
  background-color: rgba(255, 209, 220, 0.3);
}

.text-accent {
  color: var(--accent);
}

.text-dark {
  color: var(--dark);
}

/* 主图区按钮样式 */
.bg-primary {
  background-color: #FF6B8B !important;
}

.bg-primary-dark {
  background-color: #E55A7A !important;
}

.hover\:bg-primary-dark:hover {
  background-color: #E55A7A !important;
}

.hover\:border-primary:hover {
  border-color: #FF6B8B !important;
}

.hover\:text-primary:hover {
  color: #FF6B8B !important;
}

.border-primary\/30 {
  border-color: rgba(255, 107, 138, 0.3);
}

.hover\:border-primary-dark:hover {
  border-color: var(--primary-dark);
}

/* 购物车按钮样式 */
.bg-primary\/10 {
  background-color: rgba(255, 107, 139, 0.1) !important;
}

.hover\:bg-primary:hover {
  background-color: #FF6B8B !important;
}

.hover\:text-white:hover {
  color: white !important;
}

.bg-pink-50 {
  background-color: #fdf2f8;
}

.hover\:bg-pink-100:hover {
  background-color: #fce7f3;
}

.bg-white\/80 {
  background-color: rgba(255, 255, 255, 0.8);
}

/* 响应式字体大小 */
.text-\[clamp\(1\.8rem\,5vw\,3rem\)\] {
  font-size: clamp(1.8rem, 5vw, 3rem);
}

/* 自定义按钮样式 */
:deep(.el-button--primary) {
  background-color: var(--primary);
  border-color: var(--primary);
  border-radius: 9999px;
  font-weight: 600;
  transition: all 0.3s ease;
}

:deep(.el-button--primary:hover) {
  background-color: var(--primary-dark);
  border-color: var(--primary-dark);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 107, 138, 0.3);
}

/* Hero区域按钮样式 */
.hero-btn-primary {
  background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%);
  border: none;
  border-radius: 9999px;
  padding: 12px 32px;
  font-weight: 600;
  font-size: 16px;
  transition: all 0.3s ease;
}

.hero-btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(255, 107, 138, 0.4);
}

.hero-btn-secondary {
  background: transparent;
  border: 2px solid var(--primary);
  color: var(--primary);
  border-radius: 9999px;
  padding: 10px 32px;
  font-weight: 600;
  font-size: 16px;
  transition: all 0.3s ease;
}

.hero-btn-secondary:hover {
  background: var(--primary);
  color: white;
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(255, 107, 138, 0.3);
}

/* 促销按钮样式 */
.promotion-btn {
  background: white;
  color: var(--primary);
  border: none;
  border-radius: 9999px;
  padding: 12px 32px;
  font-weight: 600;
  font-size: 16px;
  transition: all 0.3s ease;
}

.promotion-btn:hover {
  background: rgba(255, 255, 255, 0.9);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .container {
    padding-left: 1rem;
    padding-right: 1rem;
  }
}

/* 卡片悬停效果 */
.card-hover {
  transition: all 0.3s ease;
}

.card-hover:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

/* 主图区按钮悬停效果 */
.hover-explore-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 15px rgba(255, 107, 139, 0.3);
  background-color: #E55A7A !important;
}

.hover-member-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
  background-color: rgba(255, 107, 139, 0.1) !important;
}

/* 促销区域按钮悬停效果 */
.hover-promotion-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
  background-color: rgba(255, 255, 255, 0.9) !important;
}

/* 定义变量 */
:root {
  --accent: #FF8FA3; /* 强调色，比primary稍微亮一点的粉色 */
  --primary-text-opacity: 1;
  --text-opacity: 1;
}

/* 订阅按钮悬停效果 */
.subscribe-btn {
  transition: all 0.3s ease;
}

.subscribe-btn:hover {
  transform: translateY(-3px) !important;
  background-color: #ff789a !important;
  box-shadow: 0 8px 15px rgba(255, 107, 139, 0.3) !important;
}

.cart-badge {
  z-index: 10;
  transform: translate(25%, -25%);
  min-width: 18px;
  height: 18px;
}
</style>
